package o2o.web.actions.order.shop;

import com.alibaba.fastjson.JSONObject;
import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import jPush.dao.JPushMessage;
import lombok.extern.slf4j.Slf4j;
import notice.dao.NoticeType;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.order.*;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysConfigDepositMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.*;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.VO.order.OrderInfoVO;
import o2o.dao.VO.order.REFUND_APPLY_STATUS;
import o2o.service.order.shop.ShopOrderService;
import o2o.system.data.SYS_SETTINGS;
import o2o.system.data.SYS_SOS_MODEL_TYPE;
import o2o.task.order.OrderTaskUtil;
import o2o.thridpost.dada.controller.DadaOrderController;
import o2o.thridpost.dada.model.to.CancelDadaOrderTO;
import o2o.web.actions.notice.Notice;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.order.thread.OverOrderThread;
import o2o.web.actions.pay.OrderPay;
import o2o.web.actions.print.PrintMan;
import o2o.web.actions.shop.ShopCategoryMan;
import o2o.web.actions.shop.ShopMan;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static notice.dao.NoticeType.order;

//店铺订单管理
@Controller
@Slf4j
public class ShopOrderController {
    @Autowired
    private DadaOrderController dadaOrderController;
    //商户确认接单
    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/sure")
    @ResponseBody
    public String order_shop_sure(String token, String sysAppKey, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null != SYS_SETTINGS.SHOP_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.SHOP_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.SHOP_OWNER);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        if (null != orderInfo.getShopSureBySys() && 0 == 1 - orderInfo.getShopSureBySys()) {
            // 后台已为商家自动接单
            return AjaxResult.errorResult("系统已为您接单，请刷新查看");
        }

        if (null != orderInfo.getShopSureTime() && orderInfo.getShopSureTime() > 0) {
            return AjaxResult.errorResult("已接单，请刷新查看");
        }


        boolean flag = true;
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (null == shopInfo) {
            flag = false;
        } else {
            if (0 == shopInfo.getId() - orderInfo.getShopId()) {
                flag = true;
            }
        }
        if (!flag) {
            return AjaxResult.errorResult("该订单不属于您的店铺");
        }
        //0 锁定  1正常
        if (0 == shopInfo.getIsLock()) {
            return AjaxResult.errorResult("您的店铺已锁定，无法接单");
        }

        ResultInfo resultInfo = sureOrder(sysAppKey, shopInfo, orderInfo, user.getUsername(), false);
        if (null != resultInfo) {
            if (!resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        } else {
            return AjaxResult.errorResult("接单失败，请稍后再试");
        }

//        //确认接单返回订单详情，用来打印（因为订单列表上未返回活动的信息）
        OrderInfoVO infoVO = OrderMan.getOrderDetail(orderNo);
        return AjaxResult.successResult(infoVO);
    }


    //店家拒绝接单
    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/refuse")
    @ResponseBody
    public String order_shop_refuse(String token, String sysAppKey, String cancelReason, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        if (null != orderInfo.getShopSureBySys() && 0 == 1 - orderInfo.getShopSureBySys()) {
            // 后台已为商家自动接单
            return AjaxResult.errorResult("系统已为您接单，请刷新查看");
        }

        if (null != orderInfo.getShopSureTime() && orderInfo.getShopSureTime() > 0) {
            return AjaxResult.errorResult("已接单，请刷新查看");
        }

        int status = orderInfo.getOrderStatus();
        if (status == ORDER_STATUS.CANCEL
                || status == ORDER_STATUS.OVER
                || status == ORDER_STATUS.CANCEL_BY_SYSTEM
                || status == ORDER_STATUS.PAYED_CANCEL
                || status == ORDER_STATUS.PEISONG
                || status == ORDER_STATUS.POSTMAN_SURE
                || status == ORDER_STATUS.POSTMAN_DAODIAN
                || status == ORDER_STATUS.POSTMAN_ZHIDING
                || status == ORDER_STATUS.SHOP_SURE) {
            return AjaxResult.errorResult("当前订单状态下不允许操作");
        }
        if (StringUtils.isEmpty(cancelReason)) {
            cancelReason = "";
        }
//        String shopSureTime = ",shopSureTime=" + DateUtils.getCurrTime() ;
        String shopSureTime = ",shopSureTime=" + DateUtils.getCurrTime() + ",postFailReason = '" + cancelReason + "',postmanFinishTime=" + DateUtils.getCurrTime();
        if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.SHOP_REFUSED, shopSureTime)) {
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }

        //拒绝接单后直接退款
//        ResultInfo resultInfo = OrderMan.cancelOrder(sysAppKey, orderInfo, user.getUsername(), "商家拒绝接单");
        ResultInfo resultInfo = OrderMan.cancelOrder(sysAppKey, orderInfo, user.getUsername(), ValidateUtil.isNotNull(cancelReason) ? cancelReason : "商家拒绝接单", true, true, false);
        if (null == resultInfo) {
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        //修改订单信息缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);


        //发送一条订单通知
//        Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），商家拒绝接单");
//
//        //极光推送
//        JPushMessage jPushMessage2 = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），商家拒绝接单");
//        jPushMessage2.setPushUserType(JPushMessage.USER);//推给用户
//        JPushTask.jPushMessageList.add(jPushMessage2);


        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），商家拒绝接单");

        return AjaxResult.successResult();
    }

    //店铺验证配送员提货码或者用户取货码
    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/verify")
    @ResponseBody
    public String order_shop_verify(String token, String sysAppKey, String verifyCode) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

//        if (!User.hasShopAuth(user.getUserType())) {
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有店铺操作权限");
        }

        if (null != SYS_SETTINGS.SHOP_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.SHOP_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.SHOP_OWNER);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }


//        if (ValidateUtil.isNull(orderNo)) {
//            return AjaxResult.errorResult("请输入订单编号");
//        }
        if (ValidateUtil.isNull(verifyCode)) {
            return AjaxResult.errorResult("请输入验证码");
        }

        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (null == shopInfo) {
            return AjaxResult.errorResult("您还没有店铺");
        }

        //0 锁定  1未锁定
        if (0 == shopInfo.getIsLock()) {
            return AjaxResult.errorResult("您的店铺已锁定，无法接单");
        }

//        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
//        if (null == orderInfo) {
//            return AjaxResult.errorResult("该订单不存在");
//        }


        //验证配送验证码
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfoByVerifyCode(verifyCode);
        if (null == orderInfo) {
            return AjaxResult.errorResult("未找到订单，请查证后验证");
        }

        if (0 != shopInfo.getId() - orderInfo.getShopId()) {
            return AjaxResult.errorResult("您店铺不存在该订单，请查证");
//            return AjaxResult.errorResult("该订单不是您店铺的，请查证");
        }

        //todo
//        if (!orderNo.equalsIgnoreCase(verifyOrderInfo.getOrderNo())) {
//            return AjaxResult.errorResult("验证码不匹配，请重试");
//        }


        Long time = DateUtils.getCurrTime();
        int status = orderInfo.getOrderStatus();
        if (0 == 1 - orderInfo.getIsZiQu()) {
            if (status == ORDER_STATUS.CANCEL
                    || status == ORDER_STATUS.OVER
                    || status == ORDER_STATUS.SHOP_FINISH
                    || status == ORDER_STATUS.SHOP_REFUSED
                    || status == ORDER_STATUS.PAYED_CANCEL
                    || status == ORDER_STATUS.POSTMAN_REFUSED
                    || status == ORDER_STATUS.POSTMAN_ZHIDING
                    || status == ORDER_STATUS.POSTMAN_FINISH) {
                return AjaxResult.errorResult("当前订单状态下不允许操作");
            }


            //修改订单及订单状态状态数据库
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.OrderInfo).append(" set updateUser = '").append(user.getUsername())
                    .append("',orderStatus=").append(ORDER_STATUS.SHOP_FINISH).append(",shopFinishTime=").append(time)
                    .append(" where delFlag =0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");

            OrderStatus orderStatus = new OrderStatus(orderInfo.getOrderNo(), ORDER_STATUS.SHOP_FINISH, user.getUsername(), time);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败，请稍后再试");
            }


            //分成
//            ResultInfo resultInfo = OrderPay.distributeMoney(orderInfo, orderInfo.getOrderNo(), user.getUsername());
            ResultInfo resultInfo = null;
            if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.GROUP_ORDER - orderInfo.getOrderType()) {
                // 团购订单
                if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
                } else {
                    resultInfo = OrderPay.distributeMoney(orderInfo, orderInfo.getOrderNo(), user.getUsername());//团购  店铺验证配送员提货码或者用户取货码
                }
            } else {
                // 团购订单
                if (null != SYS_SETTINGS.CUSTOM_SYSTEM_TYPE && SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
                } else {
                    resultInfo = OrderPay.distributeMoney(orderInfo, orderInfo.getOrderNo(), user.getUsername());//非团购  店铺验证配送员提货码或者用户取货码
                }

            }

            if (null != resultInfo && !resultInfo.isSuccess()) {
                System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
            }

        } else {
            if (status == ORDER_STATUS.CANCEL
                    || status == ORDER_STATUS.OVER
                    || status == ORDER_STATUS.SHOP_FINISH
                    || status == ORDER_STATUS.SHOP_REFUSED
                    || status == ORDER_STATUS.PAYED_CANCEL
                    || status == ORDER_STATUS.SHOP_SURE
                    || status == ORDER_STATUS.POSTMAN_REFUSED
                    || status == ORDER_STATUS.POSTMAN_ZHIDING
                    || status == ORDER_STATUS.POSTMAN_FINISH) {
                return AjaxResult.errorResult("当前订单状态下不允许操作");
            }


            //修改订单及订单状态状态数据库
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.OrderInfo).append(" set updateUser = '").append(user.getUsername())
                    .append("',orderStatus=").append(ORDER_STATUS.PEISONG).append(" where delFlag =0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");
            OrderStatus orderStatus = new OrderStatus(orderInfo.getOrderNo(), ORDER_STATUS.PEISONG, user.getUsername(), time);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败，请稍后再试");
            }

            ResultInfo resultInfo = null;
            if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.GROUP_ORDER - orderInfo.getOrderType()) {
                // 团购订单
                if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
                } else {
                    resultInfo = OrderPay.distributeMoney(orderInfo, orderInfo.getOrderNo(), user.getUsername());//团购  店铺验证配送员提货码或者用户取货码
                }
            }
            if (null != resultInfo && !resultInfo.isSuccess()) {
                System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
            }
        }


        //配送码在缓存中释放
        OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        OrderInfoMemory.getInstance().removeVerifyCode(orderInfo.getOrderNo(), verifyCode);//商家验证 验证码成功，将验证码释放
        //修改订单缓存
        //修改订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderInfo.getOrderNo());


        //插入验证记录
        OrderVerifyHistory orderVerifyHistory = new OrderVerifyHistory();
        orderVerifyHistory.setDelFlag(0);
        orderVerifyHistory.setCreateTime(time);
        orderVerifyHistory.setCreateUser(user.getUsername());
        orderVerifyHistory.setShopId(shopInfo.getId());
        orderVerifyHistory.setOrderNo(orderInfo.getOrderNo());
        orderVerifyHistory.setVerifyCode(verifyCode);
//        if (0 == 1 - orderInfo.getIsZiQu()) {
//            orderVerifyHistory.setVerifyUsername(orderInfo.getPostManUsername());
//            orderVerifyHistory.setType(OrderVerifyHistory.POSTMAN);
//        } else {
//            orderVerifyHistory.setVerifyUsername(orderInfo.getUsername());
//            orderVerifyHistory.setType(OrderVerifyHistory.ZIQU);
//        }
        if (0 == 1 - orderInfo.getIsZiQu()) {
            orderVerifyHistory.setVerifyUsername(orderInfo.getUsername());
            orderVerifyHistory.setType(OrderVerifyHistory.ZIQU);
        } else {
            orderVerifyHistory.setVerifyUsername(orderInfo.getPostManUsername());
            orderVerifyHistory.setType(OrderVerifyHistory.POSTMAN);
        }
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.ORDER_VERIFY_HISTORY, orderVerifyHistory);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("插入验证记录错误，请稍后再试");
        }
        OrderVerifyMemory.getInstance().add(time);


        OrderInfoVO orderInfoVO = new OrderInfoVO();
        try {
            ObjectUtils.copyPropertiesExclude(orderInfo, orderInfoVO, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.successResult(orderInfo);
        }

//        //发送一条订单通知
//        Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderInfo.getOrderNo() + "），已确认消费。");
//
//        //极光推送
//        JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderInfo.getOrderNo() + "），已确认消费。");
//        jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//        JPushTask.jPushMessageList.add(jPushMessage);

        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderInfo.getOrderNo() + "），已确认消费。");

        if (null != orderInfoVO) {
            AjaxResult.successResult(orderInfoVO);
        }

        return AjaxResult.successResult(orderInfo);
    }


    //商家抢单
    @RequestMapping(method = RequestMethod.POST, value = "/shop/order/grab")
    @ResponseBody
    public String order_shop_new_list_grab(String token, String sysAppKey, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null != SYS_SETTINGS.SHOP_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.SHOP_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.SHOP_OWNER);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        //是否有权限抢单
//        if (!User.hasShopAuth(user.getUserType())) {
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (null == shopInfo) {
            return AjaxResult.errorResult("您不是店主无法 操作");
        }

        //0 锁定  1未锁定
        if (0 == shopInfo.getIsLock()) {
            return AjaxResult.errorResult("您的店铺已锁定，无法接单");
        }

        if (ValidateUtil.isNull(shopInfo.getCity())) {
            return AjaxResult.errorResult("您的店铺信息不完整（无城市信息），请先填写完整");
        }
        if (ValidateUtil.isNotAbsInteger(shopInfo.getIsWork())) {
            return AjaxResult.errorResult("您无法接单，请先上班");
        }
        if (0 == shopInfo.getIsWork()) {
            return AjaxResult.errorResult("请先上班");
        }


        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("当前订单不存在");
        }

        //判断订单状态  是否可以抢单
        if (0 != ORDER_STATUS.PAYED - orderInfo.getOrderStatus()) {
            //店铺接单后才可以抢单
            return AjaxResult.errorResult("该订单当前状态下不可以抢单");
        }

        //判断抢单范围
        if (ValidateUtil.isNotAbsDouble(shopInfo.getLat()) || ValidateUtil.isNotAbsDouble(shopInfo.getLng())) {
            return AjaxResult.errorResult("您的信息不完整，请联系客服");
        }
        if (ValidateUtil.isNotAbsDouble(orderInfo.getLat()) || ValidateUtil.isNotAbsDouble(orderInfo.getLng())) {
            return AjaxResult.errorResult("超出范围，无法抢单");
        }

//        double dis = Geohash.distance(orderInfo.getLat(), orderInfo.getLng(), shopInfo.getLat(), shopInfo.getLng());
//        int range = 15;//大概是10公里
//        if (ValidateUtil.isAbsInteger(SYS_SETTINGS.SHOP_RANGE)) {
//            range = SYS_SETTINGS.SHOP_RANGE;
//        }
//        if (JYMathDoubleUtils.sub(dis, range * 1000) > 0) {
//            return AjaxResult.errorResult("超出您的范围，无法抢单");
//        }

        double dis = Geohash.distance(orderInfo.getLat(), orderInfo.getLng(), shopInfo.getLat(), shopInfo.getLng());
        int range = 15;//大概是10公里
        if (ValidateUtil.isAbsInteger(SYS_SETTINGS.SHOP_RANGE)) {
            range = SYS_SETTINGS.SHOP_RANGE;
        }
        Long agnetId = orderInfo.getAgentId();
        if (ValidateUtil.isID(agnetId)) {
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(agnetId);
            if (null != cityAgent) {
                range = cityAgent.getRang();
            }
        }

        if (JYMathDoubleUtils.sub(dis, range * 1000) > 0) {
            return AjaxResult.errorResult("超出您的范围，无法抢单");
        }



        //是否已抢过
        if (ShopGrabMemory.getInstance().hasGrabThisOrder(user.getUsername(), orderNo)) {
            return AjaxResult.errorResult("你已经抢过该订单，请耐心等待");
        }

        //判断当前订单是否被其他人抢过
        if (ShopGrabMemory.getInstance().hasGrab(orderNo)) {
            return AjaxResult.errorResult("该订单已被其他人抢了");
        }

        long time = DateUtils.getCurrTime();
        //将抢单信息加入到缓存
        OrderGrabInfo orderGrabInfo = new OrderGrabInfo(user.getUsername(), user.getName(), time, orderNo, orderInfo.getCity());
        ShopGrabMemory.getInstance().grabOrder(orderGrabInfo);
        //todo 暂时不放入数据库


        //自己去配送  不用验证码
        //直接生成配送验证码，去提货
        //生成取货验证码
//        String verifyCode = Order.getVerifyCode();
//        if (ValidateUtil.isNull(verifyCode)) {
//            return AjaxResult.errorResult("生成验证码失败，请稍后再试");
//        }

        //保存订单商户信息
        StringBuffer sInfo = new StringBuffer();
        sInfo.append(",shopId=").append(shopInfo.getId()).append(",shopName='").append(shopInfo.getShopName())
                .append("',shopPhone='").append(shopInfo.getTelephone()).append("',shopImageUrl='").append(shopInfo.getImageUrl())
                .append("',shopAddress='").append(shopInfo.getAddress()).append("',shopLat=").append(shopInfo.getLat())
                .append(",shopLng=").append(shopInfo.getLng()).append(",shopSureTime=").append(time).append(",shopCity='").append(shopInfo.getCity()).append("'");


        //修改订单信息
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(ORDER_STATUS.POSTMAN_SURE)
                .append(",updateUser='").append(user.getUsername()).append("',postmanUsername='")
                .append(user.getUsername()).append("',postmanName='").append(user.getName()).append("',postmanPhone='").append(user.getTelPhone())
                .append("',postmanImageUrl='").append(user.getSignPhoto()).append("',postmanSureTime=").append(time)
                .append(sInfo.toString())
                .append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");
        //商家确认接单
        OrderStatus shopSureStatus = new OrderStatus(orderNo, ORDER_STATUS.SHOP_SURE, user.getUsername(), time);
        //配送员抢单
        OrderStatus postmanSure = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_SURE, user.getUsername(), time);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, shopSureStatus);
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, postmanSure);
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        //更新订单支付中的商家，以备分配金额
        if (null != shopInfo) {
            updateOrderPayShop(orderNo, shopInfo.getOwnUsername(), shopInfo.getId(), user.getUsername());
        }

        //订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        //删除未分配商家的订单
        OrderInfoMemory.getInstance().removeNoShopSure(orderNo, orderInfo.getCity());


        //发送一条订单通知
//        Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），已有配送员抢单了，请耐心等待");
//
//        //极光推送
//        JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），已有配送员抢单了，请耐心等待");
//        jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//        JPushTask.jPushMessageList.add(jPushMessage);

        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），已有配送员抢单了，请耐心等待");

        return AjaxResult.successResult();
    }


    //备货完成
    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/ready")
    @ResponseBody
    public String order_shop_ready(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        boolean flag = true;
        List<ShopInfo> shopInfoList = ShopMemory.getInstance().getShopListByUserName(user.getUsername());
        if (null == shopInfoList) {
            flag = false;
        } else {
            for (int i = 0; i < shopInfoList.size(); i++) {
                if (null == shopInfoList.get(i)) {
                    continue;
                }
                if (0 == orderInfo.getShopId() - shopInfoList.get(i).getId()) {
                    flag = true;
                    break;
                }
            }
        }
        if (!flag) {
            return AjaxResult.errorResult("该订单不属于您的店铺");
        }

        int status = orderInfo.getOrderStatus();
        if (status == ORDER_STATUS.CANCEL
                || status == ORDER_STATUS.OVER
                || status == ORDER_STATUS.CANCEL_BY_SYSTEM
                || status == ORDER_STATUS.PAYED_CANCEL
                || status == ORDER_STATUS.SHOP_REFUSED
                || status == ORDER_STATUS.SHOP_READY
                || status == ORDER_STATUS.POSTMAN_PULL_GOODS
                || status == ORDER_STATUS.PEISONG) {
            return AjaxResult.errorResult("当前订单状态下不允许操作");
        }

        String shopReadyTime = ",shopReadyTime=" + DateUtils.getCurrTime();
        if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.SHOP_READY, shopReadyTime)) {
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }
        if (OrderMan.isMultipleSonOrder(orderInfo)) {
            OrderInfo parentOrder = OrderInfoMemory.getInstance().getOrderInfo(orderInfo.getParentOrderNo());
            if (parentOrder != null) {
                checkAllOrderShopReady(parentOrder, shopReadyTime, user.getUsername());
            }
        }
        return AjaxResult.successResult();
    }

    //店铺标记为已发货
    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/push")
    @ResponseBody
    public String order_shop_push(String token, String orderNo, String shopUsername) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        int status = orderInfo.getOrderStatus();
        if (status == ORDER_STATUS.CANCEL
                || status == ORDER_STATUS.OVER
                || status == ORDER_STATUS.CANCEL_BY_SYSTEM
                || status == ORDER_STATUS.PAYED_CANCEL
                || status == ORDER_STATUS.SHOP_REFUSED
                || status == ORDER_STATUS.SHOP_PUSH_GOODS
                || status == ORDER_STATUS.POSTMAN_PULL_GOODS
                || status == ORDER_STATUS.POSTMAN_FINISH
                || status == ORDER_STATUS.POSTMAN_CANT_FINISH
                || status == ORDER_STATUS.PEISONG) {
            return AjaxResult.errorResult("当前订单状态下不允许操作");
        }

        if (orderInfo.getOrderType() != null && orderInfo.getOrderType() == ORDER_TYPE.INTEGRAL_ORDER) {
            // 积分订单 直接定单
            String shopReadyTime = ",shopPushTime=" + DateUtils.getCurrTime();
            if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.SHOP_PUSH_GOODS, shopReadyTime)) {
                return AjaxResult.errorResult("操作失败，请稍后再试");
            }

        } else {
            shopUsername = ValidateUtil.isNotNull(shopUsername) ? shopUsername : user.getUsername();
            ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(shopUsername);
            if (null == shopInfo) {
                return AjaxResult.errorResult("您不是店主");
            }
            //平台配送的  需要配送员抢单
            if ((null != shopInfo.getIsSelfPost() && 0 == shopInfo.getIsSelfPost()) && (0 != orderInfo.getOrderType() - ORDER_TYPE.SHOP_ACTIVITY)) {
                if (ValidateUtil.isNull(orderInfo.getPostManUsername())) {
                    return AjaxResult.errorResult("配送员尚未抢单，无法操作");
                }
            }


            String shopReadyTime = ",shopPushTime=" + DateUtils.getCurrTime();
            if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.SHOP_PUSH_GOODS, shopReadyTime)) {
                return AjaxResult.errorResult("操作失败，请稍后再试");
            }
            OrderInfoMemory.getInstance().removeVerifyCode(orderNo, orderInfo.getVerifyCode());//商家点击已发货，将验证码释放
        }
        return AjaxResult.successResult();
    }

    // 自取订单  商家标记为已完成
    @RequestMapping(method = RequestMethod.POST, value = "/order/ziqu/shop/finish")
    @ResponseBody
    public String order_2shop_verify(String token, String sysAppKey, Integer finishByAdmin, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        boolean finishBySys = false;
        if (null != finishByAdmin && finishByAdmin == 1) {
            finishBySys = true;
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有店铺操作权限");
        }


        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("未找到订单，请查证后验证");
        }
        ShopInfo shopInfo = null;
        if (finishBySys) {
            if (ValidateUtil.isNotID(orderInfo.getShopId())) {
                return AjaxResult.errorResult("订单店铺不存在");
            }
            shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
        } else {
            shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        }
        // 获取店铺信息
        if (null == shopInfo) {
            return AjaxResult.errorResult("店铺信息不存在");
        }

        if (!finishBySys) {
            if (0 != shopInfo.getId() - orderInfo.getShopId()) {
                return AjaxResult.errorResult("您店铺不存在该订单，请查证");
            }
        }

        if (null != SYS_SETTINGS.SHOP_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.SHOP_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(shopInfo.getOwnUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.SHOP_OWNER);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("缴纳的押金不足，请先缴纳押金");
            }
        }


        //0 锁定  1未锁定
        if (0 == shopInfo.getIsLock()) {
            return AjaxResult.errorResult("店铺已锁定，无法操作");
        }


        Long time = DateUtils.getCurrTime();
        int status = orderInfo.getOrderStatus();
        if (0 == orderInfo.getIsZiQu()) {
            return AjaxResult.errorResult("配送订单，无法操作");
        } else {
            if (status == ORDER_STATUS.CANCEL
                    || status == ORDER_STATUS.OVER
                    || status == ORDER_STATUS.CANCEL_BY_SYSTEM
                    || status == ORDER_STATUS.SHOP_FINISH
                    || status == ORDER_STATUS.SHOP_REFUSED
                    || status == ORDER_STATUS.PAYED_CANCEL
                    || status == ORDER_STATUS.POSTMAN_REFUSED
                    || status == ORDER_STATUS.POSTMAN_ZHIDING
                    || status == ORDER_STATUS.POSTMAN_FINISH) {
                return AjaxResult.errorResult("当前订单状态下不允许操作");
            }

            //修改订单及订单状态状态数据库
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.OrderInfo).append(" set updateUser = '").append(user.getUsername())
                    .append("',orderStatus=").append(ORDER_STATUS.SHOP_FINISH).append(",shopFinishTime=").append(time)
                    .append(" where delFlag =0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");

            OrderStatus orderStatus = new OrderStatus(orderInfo.getOrderNo(), ORDER_STATUS.SHOP_FINISH, user.getUsername(), time);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败，请稍后再试");
            }


            // 判断是一乙模式下的话，跳转到一乙方法里
            if (null != SYS_SETTINGS.CUSTOM_SYSTEM_TYPE && SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {

            } else {
                //分成
                ResultInfo resultInfo = OrderPay.distributeMoney(orderInfo, orderInfo.getOrderNo(), user.getUsername());// 自取订单  商家标记为已完成
                if (null != resultInfo && !resultInfo.isSuccess()) {
                    System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
                }
            }

        }


        //配送码在缓存中释放
        OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        OrderInfoMemory.getInstance().removeVerifyCode(orderInfo.getOrderNo(), orderInfo.getVerifyCode());//商家验证 验证码成功，将验证码释放

        //修改订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderInfo.getOrderNo());


        //插入验证记录
        OrderVerifyHistory orderVerifyHistory = new OrderVerifyHistory();
        orderVerifyHistory.setDelFlag(0);
        orderVerifyHistory.setCreateTime(time);
        orderVerifyHistory.setCreateUser(user.getUsername());
        orderVerifyHistory.setShopId(shopInfo.getId());
        orderVerifyHistory.setOrderNo(orderInfo.getOrderNo());
        orderVerifyHistory.setVerifyCode(orderInfo.getVerifyCode());
        orderVerifyHistory.setNote("店铺未验证取货码");
        if (0 == 1 - orderInfo.getIsZiQu()) {
            orderVerifyHistory.setVerifyUsername(orderInfo.getUsername());
            orderVerifyHistory.setType(OrderVerifyHistory.ZIQU);
        } else {
            orderVerifyHistory.setVerifyUsername(orderInfo.getPostManUsername());
            orderVerifyHistory.setType(OrderVerifyHistory.POSTMAN);
        }
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.ORDER_VERIFY_HISTORY, orderVerifyHistory);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("插入验证记录错误，请稍后再试");
        }
        OrderVerifyMemory.getInstance().add(time);


        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderInfo.getOrderNo() + "），已确认消费。");


        return AjaxResult.successResult();
    }


    //同意用户的取消订单申请
    @RequestMapping(method = RequestMethod.POST, value = "/order/cancel/pass")
    @ResponseBody
    public String order_cancel_pass(String token, String sysAppKey, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        if (REFUND_APPLY_STATUS.APPLY != orderInfo.getIsRefundApply()) {
            return AjaxResult.errorResult("无效操作【已审核过或用户未申请】");
        }

        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("订单已结束，无法操作");
        }
        // 聚合订单
        if (OrderMan.isMultipleSonOrder(orderInfo)) {
            ResultInfo resultInfo = OrderMan.shopPassSonOrderCancelApply(sysAppKey, orderInfo, true, null, user.getUsername());
            if (resultInfo == null || !resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo == null ? "操作失败,请稍后重试" : resultInfo.getError());
            }
            return AjaxResult.successResult();
        }

        //取消订单（更新订单信息为已取消，更新商品信息）
        ResultInfo resultInfo = OrderMan.cancelOrder(sysAppKey, orderInfo, user.getUsername(), orderInfo.getCancelReason(), true, true, false);
        if (null == resultInfo) {
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        //更新用户订单申请
        //更新订单信息
        StringBuffer sb = new StringBuffer();
        sb.append("update  ").append(PojoTables.OrderInfo).append(" set isRefundApply = ").append(REFUND_APPLY_STATUS.PASS)
                .append(",updateUser ='").append(user.getUsername()).append("'  where delFlag = 0 and orderNo = '").append(orderNo).append("'");
        System.out.println("同意退款:" + DateUtils.sdfDateTime.get().format(new Date()) + ":" + sb.toString());
        try {
            // 如果是第三方配送, 调第三方的取消接口
            if (orderInfo.getIsOtherPost() == 1) {
                // 达达取消订单
                CancelDadaOrderTO cancelDadaOrderTO = new CancelDadaOrderTO();
                cancelDadaOrderTO.setOrderId(orderNo);
                String orderResult = dadaOrderController.cancelOrder(cancelDadaOrderTO);
                JSONObject orderResultObject = JSONObject.parseObject(orderResult);
                Integer status = orderResultObject.getInteger("status");
                if (status != null && status == 0) {
                    log.error("达达订单取消失败, orderNo: {}, msg: {}", orderNo, orderResultObject.getString("msg"));
                    return AjaxResult.errorResult("达达订单取消失败, msg: {}", orderResultObject.getString("msg"));
                } else {
                    UserDaoSql.getInstance().executeBySql(sb.toString());
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }
        //修改订单信息缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        return AjaxResult.successResult();
    }

    // 商家主动取消订单
    @RequestMapping(method = RequestMethod.POST, value = "/shop/active/cancel/order")
    @ResponseBody
    public String shop_order_cancel_(String token, String sysAppKey, String reason, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        if (orderInfo.getOrderStatus() - ORDER_STATUS.SUBMIT == 0
                || orderInfo.getOrderStatus() - ORDER_STATUS.PAYED == 0
                || orderInfo.getOrderStatus() - ORDER_STATUS.CANCEL == 0
                || orderInfo.getOrderStatus() - ORDER_STATUS.CANCEL_BY_SYSTEM == 0
                || orderInfo.getOrderStatus() - ORDER_STATUS.PAYED_CANCEL == 0) {
            return AjaxResult.errorResult("当前状态下不允许操作");
        }
        if (orderInfo.getIsRefundApply() != null && orderInfo.getIsRefundApply() == REFUND_APPLY_STATUS.PASS) {
            return AjaxResult.errorResult("订单已经取消");
        }
        // 聚合订单
        if (OrderMan.isMultipleSonOrder(orderInfo)) {
            ResultInfo resultInfo = OrderMan.shopPassSonOrderCancelApply(sysAppKey, orderInfo, true, null, user.getUsername());
            if (resultInfo == null || !resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo == null ? "操作失败,请稍后重试" : resultInfo.getError());
            }
            return AjaxResult.successResult();
        }
        //取消订单（更新订单信息为已取消，更新商品信息）
        ResultInfo resultInfo = OrderMan.cancelOrder(sysAppKey, orderInfo, user.getUsername(), reason, true, true, true);
        if (null == resultInfo) {
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        if (orderInfo.getIsRefundApply() != null && (orderInfo.getIsRefundApply() - REFUND_APPLY_STATUS.APPLY == 0 || orderInfo.getIsRefundApply() - REFUND_APPLY_STATUS.NO_PASS == 0)) {
            //更新订单信息
            StringBuffer sb = new StringBuffer();
            sb.append("update  ").append(PojoTables.OrderInfo).append(" set isRefundApply = ").append(REFUND_APPLY_STATUS.PASS)
                    .append(",updateUser ='").append(user.getUsername()).append("'  where delFlag = 0 and orderNo = '").append(orderNo).append("'");
            System.out.println("商家主动退款:" + DateUtils.sdfDateTime.get().format(new Date()) + ":" + sb.toString());
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
                // 如果是第三方配送, 调第三方的取消接口
                if (orderInfo.getIsOtherPost() == 1) {
                    // 达达取消订单
                    CancelDadaOrderTO cancelDadaOrderTO = new CancelDadaOrderTO();
                    cancelDadaOrderTO.setOrderId(orderNo);
                    String orderResult = dadaOrderController.cancelOrder(cancelDadaOrderTO);
                    JSONObject orderResultObject = JSONObject.parseObject(orderResult);
                    Integer status = orderResultObject.getInteger("status");
                    if (status != null && status == 0) {
                        log.error("达达订单取消失败, orderNo: {}, msg: {}", orderNo, orderResultObject.getString("msg"));
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败，请稍后再试");
            }
            //修改订单信息缓存
            OrderInfoMemory.getInstance().modifyStatus(orderNo);
        }
        return AjaxResult.successResult();
    }


    //拒绝用户的取消订单申请
    @RequestMapping(method = RequestMethod.POST, value = "/order/cancel/refuse")
    @ResponseBody
    public String order_cancel_refuse(String token, String sysAppKey, String orderNo, String reBackReason) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

//        if (!User.hasShopAuth(user.getUserType())) {
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        if (REFUND_APPLY_STATUS.APPLY != orderInfo.getIsRefundApply()) {
            return AjaxResult.errorResult("无效操作【已审核过或用户未申请】");
        }
        // 一乙  取消订单
        if (OrderMan.isMultipleSonOrder(orderInfo)) {
            ResultInfo resultInfo = OrderMan.shopPassSonOrderCancelApply(sysAppKey, orderInfo, false, reBackReason, user.getUsername());
            if (resultInfo == null || !resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo == null ? "操作失败,请稍后重试" : resultInfo.getError());
            }
            return AjaxResult.successResult();
        }

        //更新订单信息
        StringBuffer sb = new StringBuffer();
        sb.append("update  ").append(PojoTables.OrderInfo).append(" set isRefundApply = ").append(REFUND_APPLY_STATUS.NO_PASS)
                .append(",updateUser ='").append(user.getUsername()).append("',reBackReason='").append(reBackReason)
                .append("'  where delFlag = 0 and orderNo = '").append(orderNo).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }

        //修改订单信息缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);

        //加入自动完成订单
        if (ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus() || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()) {
            OverOrderThread.map.put(orderNo, orderInfo);
        }

        //发送一条订单通知
//        Notice.publishOrderNotice(user.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），申请取消未通过，如有疑问可联系客服");
//
//        //极光推送
//        JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），申请取消未通过");
//        jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//        JPushTask.jPushMessageList.add(jPushMessage);

        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），申请取消未通过");
        return AjaxResult.successResult();
    }

    // 同意用户取消部分商品
    @RequestMapping(method = RequestMethod.POST, value = "/order/part/cancel/pass")
    @ResponseBody
    public String order_part_cancel_pass(String token, String sysAppKey, String orderNo, Double backTotalPrice, String backOrderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
//        if (!User.hasShopAuth(user.getUserType())) {
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        if (REFUND_APPLY_STATUS.APPLY != orderInfo.getIsPartCancelApply()) {
            return AjaxResult.errorResult("无效操作【已审核过或用户未申请】");
        }
        if (ValidateUtil.isNull(backOrderNo)) {
            return AjaxResult.errorResult("退款订单信息不能为空");
        }
        OrderCancelInfo orderCancelInfo = OrderCancelInfoMemory.getInstance().get(backOrderNo);
        if (orderCancelInfo == null) {
            return AjaxResult.errorResult("取消订单信息不存在，请核实");
        }
        //
        if (orderCancelInfo.getIsPartCancelApply() != REFUND_APPLY_STATUS.APPLY) {
            return AjaxResult.errorResult("无效操作【已审核过或用户未申请】");
        }
        // 退多少钱 设置
        double backTotalGoodsMoney = 0.0d;
        double backTotalPacketMoney = 0.0d;
        double backTotalMoney = 0.0d;
        if (ValidateUtil.isAbsDouble(backTotalPrice)) {
            backTotalMoney = backTotalPrice;
            if (JYMathDoubleUtils.sub(orderCancelInfo.getBackTotalMoney(), backTotalPrice) < 0) {
                return AjaxResult.errorResult("退款金额不能大于申请金额");
            }
            backTotalGoodsMoney = orderCancelInfo.getBackTotalGoodsMoney();
            if (backTotalGoodsMoney >= backTotalPrice) {
                backTotalGoodsMoney = backTotalPrice;
            } else {
                backTotalPacketMoney = JYMathDoubleUtils.sub(backTotalPrice, backTotalGoodsMoney);
            }
        } else {
            backTotalMoney = orderCancelInfo.getBackTotalMoney();
            backTotalGoodsMoney = orderCancelInfo.getBackTotalGoodsMoney();
            backTotalPacketMoney = orderCancelInfo.getBackTotalPacketMoney() == null ? 0.0d : orderCancelInfo.getBackTotalPacketMoney();
        }
        // 钱数设定完毕
        // 退款还是修改  需要根据状态判断
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
        ResultInfo resultInfo = OrderMan.partCancelOrder(orderInfo, shopInfo, orderInfo.getOrderStatus(), orderNo, backOrderNo, backTotalMoney, backTotalGoodsMoney, backTotalPacketMoney, user.getUsername(), true);
        if (resultInfo == null) {
            return AjaxResult.errorResult("操作失败，请稍重试");
        }
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        // 极光推送
        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, order, "订单信息", "您的订单（订单编号：" + orderNo + "），申请已通过");
        return AjaxResult.successResult();
    }

    //拒绝用户的部分退款申请
    @RequestMapping(method = RequestMethod.POST, value = "/order/part/cancel/refuse")
    @ResponseBody
    public String order_part_cancel_refuse(String token, String sysAppKey, String orderNo, String backOrderNo, String reBackReason) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
//        if (!User.hasShopAuth(user.getUserType())) {
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        if (REFUND_APPLY_STATUS.APPLY != orderInfo.getIsPartCancelApply()) {
            return AjaxResult.errorResult("无效操作【已审核过或用户未申请】");
        }
        if (ValidateUtil.isNull(backOrderNo)) {
            return AjaxResult.errorResult("退款订单信息不能为空");
        }
        OrderCancelInfo orderCancelInfo = OrderCancelInfoMemory.getInstance().get(backOrderNo);
        if (orderCancelInfo == null) {
            return AjaxResult.errorResult("取消订单信息不存在，请核实");
        }
        //
        if (orderCancelInfo.getIsPartCancelApply() != REFUND_APPLY_STATUS.APPLY) {
            return AjaxResult.errorResult("无效操作【已审核过或用户未申请】");
        }
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("数据库连接异常");
        }

        //更新订单信息
        StringBuffer sb = new StringBuffer();
        sb.append("update  ").append(PojoTables.OrderInfo).append(" set isPartCancelApply = ").append(REFUND_APPLY_STATUS.NO_PASS)
                .append(",updateUser ='").append(user.getUsername()).append("'  where delFlag = 0 and orderNo = '").append(orderNo).append("'");
        // 更新取消订单信息

        StringBuffer cancelSql = new StringBuffer();
        cancelSql.append("update ").append(PojoTables.ORDER_CANCEL_INFO).append(" set isPartCancelApply=").append(REFUND_APPLY_STATUS.NO_PASS)
                .append(",updateUser ='").append(user.getUsername()).append("' ")
                .append(",reBackTime=").append(DateUtils.getCurrTime());
        if (!ValidateUtil.isNull(reBackReason)) {
            cancelSql.append(",reBackReason='").append(reBackReason).append("' ");
        }
        cancelSql.append("  where delFlag = 0 and orderNo = '").append(backOrderNo).append("'");
        // 添加一种状态
        // 添加一种状态  但仅仅的状态
        Long tim = DateUtils.getCurrTime();
        OrderStatus status = new OrderStatus(orderNo, ORDER_STATUS.PAYED_REFUND_PART_CANCEL, user.getUsername(), tim);
        status.setNote(reBackReason);
        try {
            UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, status, conn);
            UserDaoSql.getInstance().executeBySql(sb.toString(), conn);
            UserDaoSql.getInstance().executeBySql(cancelSql.toString(), conn);
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            UserDaoSql.getInstance().close(conn);
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }
        try {
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            return AjaxResult.errorResult("操作失败，请稍后重试");
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        //修改订单信息缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        OrderCancelInfoMemory.getInstance().modify(backOrderNo);
        //
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //加入自动完成订单
        if (ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus() || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()) {
            OverOrderThread.map.put(orderNo, orderInfo);
        }

        //发送一条订单通知
//        Notice.publishOrderNotice(user.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），申请取消未通过，如有疑问可联系客服");
//
//        //极光推送
//        JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），申请取消未通过");
//        jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//        JPushTask.jPushMessageList.add(jPushMessage);

        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），申请退款未通过");
        return AjaxResult.successResult();
    }


    //自配送订单确认完成
    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/finish")
    @ResponseBody
    public String order_shop_finish(String token, String sysAppKey, String orderNo, String shopUserName,
                                    Double lat, Double lng, String province, String city, String county, String address) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

//        if (!User.hasShopAuth(user.getUserType())) {
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        if (orderInfo.getOrderType() != null && orderInfo.getOrderType() == ORDER_TYPE.INTEGRAL_ORDER) {
            // 积分订单
            Long time = DateUtils.getCurrTime();
            //修改订单状态为配送员已接单
            //修改数据库
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(ORDER_STATUS.POSTMAN_FINISH)
                    .append(",updateUser='").append(user.getUsername()).append("',postmanFinishTime=").append(time)
                    .append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");

            OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_FINISH, user.getUsername(), time);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败，请稍后重试");
            }

            //修改订单状态缓存
            OrderStatusMemory.getInstance().addStatus(orderNo);
            //修改缓存
            OrderInfoMemory.getInstance().modifyStatus(orderNo);

            OverOrderThread.map.put(orderNo, orderInfo);//加入自动完成线程，超时未确认的  系统确认完成
        } else {
            //获取店铺信息
            shopUserName = ValidateUtil.isNotNull(shopUserName) ? shopUserName : user.getUsername();
            ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(shopUserName);
            if (null == shopInfo) {
                return AjaxResult.errorResult("您不是商家无法操作");
            }
            //获取店铺类型 是否自配送
            if (0 == shopInfo.getIsSelfPost()) {
                return AjaxResult.errorResult("平台配送订单，您无法操作");
            }

            //该订单是否已经转给别人
            if (ValidateUtil.isNotNull(orderInfo.getChangePostman())) {
                return AjaxResult.errorResult("您已发起转单请求，请等待对方应答");
            }

            //判断订单状态是否可以操作
            if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                    || ORDER_STATUS.PAYED == orderInfo.getOrderStatus()
                    || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                    || ORDER_STATUS.SUBMIT == orderInfo.getOrderStatus()
                    || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                    || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                    || ORDER_STATUS.POSTMAN_SURE == orderInfo.getOrderStatus()
                    || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                    || ORDER_STATUS.POSTMAN_REFUSED == orderInfo.getOrderStatus()
                    || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()) {
                return AjaxResult.errorResult("该状态不允许操作");
            }

            // create by yangtk
            // 货到付款订单 货到付款订单嫩自己完成
//            if (ValidateUtil.isAbsInteger(orderInfo.getIsArrivePay()) && 0 == 1 - orderInfo.getIsArrivePay()) {
//                if (orderInfo.getIsPaid() != null && 0 == 1 - orderInfo.getIsPaid()) {
//                    // 已经支付
//                } else {
//                    return AjaxResult.errorResult("货到付款订单用户尚未支付");
//                }
//            }
            // end

            Long time = DateUtils.getCurrTime();
            //修改订单状态为配送员已接单
            //修改数据库
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(ORDER_STATUS.POSTMAN_FINISH)
                    .append(",updateUser='").append(shopUserName).append("',postmanFinishTime=").append(time)
                    .append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");

            OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_FINISH, shopUserName, time);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败，请稍后重试");
            }

            //修改订单状态缓存
            OrderStatusMemory.getInstance().addStatus(orderNo);
            //修改缓存
            OrderInfoMemory.getInstance().modifyStatus(orderNo);


            //更新订单支付中的配送员，以备分配金额
//        updateOrderPayPostman(orderNo, user.getUsername(), user.getUsername());

//            //分成
//            if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
//                ResultInfo resultInfo = OrderPay.distributeMoney(orderInfo, orderNo, user.getUsername());
//                if (null != resultInfo && !resultInfo.isSuccess()) {
//                    System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
//                }
//
//                OverOrderThread.map.put(orderNo, orderInfo);//加入自动完成线程，超时未确认的  系统确认完成
//            }

            //分成
            if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
                if (null == orderInfo.getIsArrivePay() || orderInfo.getIsArrivePay() != 1) { // 不是线下付款 则需要分成
//                    ResultInfo resultInfo = OrderPay.distributeMoney(orderInfo, orderNo, shopUserName); //自配送订单确认完成
//                    if (null != resultInfo && !resultInfo.isSuccess()) {
//                        System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
//                    }

                    ResultInfo resultInfo = null;
                    if (null != SYS_SETTINGS.CUSTOM_SYSTEM_TYPE && SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
                    } else {
                        resultInfo = OrderPay.distributeMoney(orderInfo, orderNo, shopUserName); //自配送订单确认完成
                    }
                    if (null != resultInfo && !resultInfo.isSuccess()) {
                        System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
                    }
                }

                OverOrderThread.map.put(orderNo, orderInfo);//加入自动完成线程，超时未确认的  系统确认完成
            }


            //保存配送员确认送达位置
//        if (ValidateUtil.isAbsDouble(lat) && ValidateUtil.isAbsDouble(lng)) {
            if (null != lat && null != lng) {
                OrderOtherInfo info = new OrderOtherInfo();
                info.setOrderNo(orderNo);
                info.setLat(lat);
                info.setLng(lng);
                info.setProvince(province);
                info.setCity(city);
                info.setCounty(county);
                info.setAddress(address);
                info.setCreateTime(time);
                info.setDelFlag(0);
                info.setCreateUser(shopUserName);
                try {
                    UserDaoSql.getInstance().insertObj(PojoTables.ORDER_OTHER, info);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            //非开锁订单需要推送给用户一条配送员确认送达的消息
            if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
                //发送一条订单通知
//            Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已确认送达，请尽快确认订单完成");
//            //极光推送
//            JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已确认送达，请尽快确认订单完成");
//            jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//            JPushTask.jPushMessageList.add(jPushMessage);

                Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已确认送达，请尽快确认订单完成");

            }

        }

        return AjaxResult.successResult();
    }

    // 商家送达提货点
    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/post/point")
    @ResponseBody
    public String order_shop_pull_point(String token, String sysAppKey, String orderNo,
                                        Double lat, Double lng, String province, String city, String county, String address) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        //获取店铺信息
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (null == shopInfo) {
            return AjaxResult.errorResult("您不是商家无法操作");
        }
        //获取店铺类型 是否自配送
        if (0 == shopInfo.getIsSelfPost()) {
            return AjaxResult.errorResult("平台配送订单，您无法操作");
        }

        //该订单是否已经转给别人
        if (ValidateUtil.isNotNull(orderInfo.getChangePostman())) {
            return AjaxResult.errorResult("您已发起转单请求，请等待对方应答");
        }

        //判断订单状态是否可以操作
        if (ORDER_STATUS.SHOP_SURE != orderInfo.getOrderStatus()
                && ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_SUER != orderInfo.getOrderStatus()
                && ORDER_STATUS.SHOP_PUSH_GOODS != orderInfo.getOrderStatus()
        ) {
            return AjaxResult.errorResult("该状态不允许操作");
        }

        Long time = DateUtils.getCurrTime();
        String postmanPostPointTimeStr = "";
        postmanPostPointTimeStr = ",postmanPostPointTime = " + time;
        if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.POSTMAN_PICK_POINT, postmanPostPointTimeStr)) {
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        // 保存位置
        if (null != lat && null != lng) {
            OrderOtherInfo info = new OrderOtherInfo();
            info.setOrderNo(orderNo);
            info.setLat(lat);
            info.setLng(lng);
            info.setProvince(province);
            info.setCity(city);
            info.setCounty(county);
            info.setAddress(address);
            info.setCreateTime(time);
            info.setDelFlag(0);
            info.setCreateUser(user.getUsername());
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ORDER_OTHER, info);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），商家已送达提货点，等待众包取货");

        }
        return AjaxResult.successResult();
    }

    // 商家确认发货填写订单号等
    @RequestMapping(method = RequestMethod.POST, value = "/order/add/extra")
    @ResponseBody
    public String order_add_expressNo(String token, OrderInfoExtra infoExtra) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(infoExtra.getOrderNo())) {
            return AjaxResult.errorResult("订单编号不能为空");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(infoExtra.getOrderNo());
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        if (ValidateUtil.isNull(infoExtra.getExpressNo())) {
            return AjaxResult.errorResult("快递单号不能为空");
        }
        // 附表
        OrderInfoExtra orderInfoExtra = OrderInfoExtraMemory.getInstance().getOrderInfoExtraByOrderNo(infoExtra.getOrderNo());
//        if (null != orderInfoExtra) {
//            return AjaxResult.errorResult("信息错误");
//        }
        long time = DateUtils.getCurrTime();
        if (null != orderInfoExtra) {
            StringBuffer sb = new StringBuffer();
            sb.append("update  ").append(PojoTables.ORDER_INFO_EXTRA).append(" set expressNo = '").append(infoExtra.getExpressNo())
                    .append("',expressName = '").append(infoExtra.getExpressName()).append("',expressTime =").append(time)
                    .append(",updateUser ='").append(user.getUsername()).append("'  where delFlag = 0 and orderNo = '").append(infoExtra.getOrderNo()).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败，请稍后再试");
            }
        } else {
            infoExtra.setCreateTime(time);
            infoExtra.setDelFlag(0);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ORDER_INFO_EXTRA, infoExtra);
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("添加失败，请稍后再试");
            }
        }
        // 增加缓存
        OrderInfoExtraMemory.getInstance().add(infoExtra.getOrderNo());

        return AjaxResult.successResult();
    }


    // 商家收入明细
    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/income/history")
    @ResponseBody
    public String order_shop_income_history(String token, Long shopId, Long startTime, Long endTime, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("你没有店铺权限");
        }
        ShopInfo shopInfo = null;
        if (ValidateUtil.isNotID(shopId)) {
            shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
            shopId = shopInfo.getId();
        } else {
            shopInfo = ShopMemory.getInstance().getShopById(shopId);
        }
        if (shopInfo == null) {
            return AjaxResult.errorResult("店铺不存在，请核实");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        // 优齐返回数据不够 先这麽做 手机端就不用升级了
        boolean isAll = false;
        if (size > 1000) {
            isAll = true;
        }

        StringBuilder sql = new StringBuilder();
        sql.append(" select ")
                .append(" I.*, ")
//                .append(" I.orderNo AS orderNo, ")
//                .append(" I.createTime AS createTime, ")
                .append(" IFNULL(O.shopMoney,0)  AS shopMoney ")
                .append(" FROM ")
                .append(PojoTables.OrderInfo).append(" AS I ")
                .append("  LEFT JOIN ")
                .append(PojoTables.OrderPay).append(" as O ")
                .append(" ON I.orderNo = O.orderNo ")
                .append(" WHERE I.shopId = ").append(shopId)
                .append(" AND I.orderStatus = 9 ")
                .append(" AND I.isRefundApply != 2 ")
                .append("  AND I.orderNo not like 'P%'")
                .append("  AND I.delFlag = 0 ");
        // 结束时间
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" AND I.createTime > ").append(startTime);
        }
        // 开始时间
        if (ValidateUtil.isAbsLong(endTime)) {
            sql.append(" AND I.createTime < ").append(endTime);
        }
        sql.append(" AND O.isOrderCancel = 0 ")
                .append("  AND O.delFlag = 0 ")
                .append("  AND O.isPaid = 1 ")
                .append(" ORDER BY createtime DESC ");
        List<HashMap<String, Object>> list = null;
        try {
            list = UserDaoSql.getInstance().queryBySql(sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后重试");
        }
        if (ValidateUtil.isAbsList(list)) {
            if (!isAll) {
                if (ValidateUtil.isAbsList(list)) {
                    JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
                    if (ValidateUtil.isAbsList(pageList.list)) {
                        return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
                    }
                }
            } else {
                return AjaxResult.successResult(list, list.size());
            }
        }
        // 没有更多了
        return AjaxResult.successResult(null, 0);
    }

    // 商家收入明细
    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/income/history/info")
    @ResponseBody
    public String order_shop_income_history_info(String token, Long shopId, Long startTime, Long endTime, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("你没有店铺权限");
        }
        ShopInfo shopInfo = null;
        if (ValidateUtil.isNotID(shopId)) {
            shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
            shopId = shopInfo.getId();
        } else {
            shopInfo = ShopMemory.getInstance().getShopById(shopId);
        }
        if (shopInfo == null) {
            return AjaxResult.errorResult("店铺不存在，请核实");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" select ")
                .append(" I.orderNo AS orderNo, ")
                .append(" I.createTime AS createTime, ")
                .append(" IFNULL(O.shopMoney,0)  AS shopMoney ")
                .append(" FROM ")
                .append(PojoTables.OrderInfo).append(" AS I ")
                .append("  LEFT JOIN ")
                .append(PojoTables.OrderPay).append(" as O ")
                .append(" ON I.orderNo = O.orderNo ")
                .append(" WHERE I.shopId = ").append(shopId)
                .append(" AND I.orderStatus = 9 ")
                .append(" AND I.isRefundApply != 2 ")
                .append("  AND I.delFlag = 0 ");
        // 结束时间
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" AND I.createTime > ").append(startTime);
        }
        // 开始时间
        if (ValidateUtil.isAbsLong(endTime)) {
            sql.append(" AND I.createTime < ").append(endTime);
        }
        sql.append(" AND O.isOrderCancel = 0 ")
                .append("  AND O.delFlag = 0 ")
                .append("  AND O.isPaid = 1 ")
                .append(" ORDER BY createtime DESC ");
        List<HashMap<String, Object>> list = null;
        try {
            list = UserDaoSql.getInstance().queryBySql(sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后重试");
        }
        if (ValidateUtil.isAbsList(list)) {
            Double totalMoney = 0.0d;
            for (HashMap<String, Object> map : list) {
                if (map != null && !ValidateUtil.isNull(map.get("shopMoney"))) {
                    try {
                        Double d = Double.parseDouble(map.get("shopMoney").toString());
                        if (d != null) {
                            totalMoney = JYMathDoubleUtils.add(totalMoney, d);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("totalMoney", totalMoney);
            JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
            resultMap.put("totalCount", pageList.totalCount);
            resultMap.put("size", pageList.size);
            resultMap.put("data", pageList.list);
            return AjaxResult.successResult(resultMap);
        }
        // 没有更多了
        return AjaxResult.successResult();
    }

    // 团购商家核销订单
    //店铺核销当前订单信息
    @RequestMapping(method = RequestMethod.POST, value = "/group/order/shop/verify")
    @ResponseBody
    public String group_order_shop_verify(String token, String sysAppKey, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有店铺操作权限");
        }

        if (null != SYS_SETTINGS.SHOP_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.SHOP_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.SHOP_OWNER);
            if (null == money) {
                money = 0d;
            }
            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (shopInfo == null) {
            return AjaxResult.errorResult("未获取到商家信息");
        }
        if (!ShopCategoryMan.validGroupShopType(shopInfo.getShopCategory())) {
            return AjaxResult.errorResult("您不是团购商家");
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单号不能为空");
        }

        //0 锁定  1未锁定
        if (0 == shopInfo.getIsLock()) {
            return AjaxResult.errorResult("您的店铺已锁定，无法接单");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("未找到订单，请查证后验证");
        }
        if (0 != shopInfo.getId() - orderInfo.getShopId()) {
            return AjaxResult.errorResult("您店铺不存在该订单，请查证");
        }
        Long time = DateUtils.getCurrTime();
        int status = orderInfo.getOrderStatus();
        if (status == ORDER_STATUS.CANCEL
                || status == ORDER_STATUS.OVER
                || status == ORDER_STATUS.SHOP_FINISH
                || status == ORDER_STATUS.SHOP_REFUSED
                || status == ORDER_STATUS.PAYED_CANCEL
                || status == ORDER_STATUS.POSTMAN_REFUSED
                || status == ORDER_STATUS.POSTMAN_ZHIDING
                || status == ORDER_STATUS.POSTMAN_FINISH) {
            return AjaxResult.errorResult("当前订单状态下不允许操作");
        }
        //修改订单及订单状态状态数据库
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set updateUser = '").append(user.getUsername())
                .append("',orderStatus=").append(ORDER_STATUS.OVER).append(",shopFinishTime=").append(time)
                .append(" where delFlag =0 and orderNo = '").append(orderInfo.getOrderNo()).append("'");
        OrderStatus orderStatus = new OrderStatus(orderInfo.getOrderNo(), ORDER_STATUS.SHOP_FINISH, user.getUsername(), time);
        OrderStatus orderStatus2 = new OrderStatus(orderInfo.getOrderNo(), ORDER_STATUS.OVER, user.getUsername(), time);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus2);
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }

        ResultInfo resultInfo = null;
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
        } else {
            resultInfo = OrderPay.distributeMoney(orderInfo, orderInfo.getOrderNo(), user.getUsername());// 团购商家核销订单
        }
        //分成
//        resultInfo = OrderPay.distributeMoney(orderInfo, orderInfo.getOrderNo(), user.getUsername());
        if (null != resultInfo && !resultInfo.isSuccess()) {
            System.out.println("完成订单，但是分配金额失败：" + resultInfo.getError());
        }
        //修改订单缓存
        //修改订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderInfo.getOrderNo());
        OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        OrderInfoVO orderInfoVO = new OrderInfoVO();
        try {
            ObjectUtils.copyPropertiesExclude(orderInfo, orderInfoVO, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.successResult(orderInfo);
        }
        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderInfo.getOrderNo() + "），已确认消费。");
        if (null != orderInfoVO) {
            AjaxResult.successResult(orderInfoVO);
        }
        return AjaxResult.successResult(orderInfo);
    }

    /**
     * -------------------------
     */
    //更新店主
    private boolean updateOrderPayShop(String orderNo, String sellerUsername, Long sellerId, String opUsername) {
        if (ValidateUtil.isNull(orderNo)) {
            return false;
        }
        if (ValidateUtil.isNull(sellerUsername)) {
            return false;
        }

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.OrderPay).append(" set seller = '").append(sellerUsername).append("',sellerId=").append(sellerId).append(",updateUser='").append(opUsername)
                .append("' where orderNo = '").append(orderNo).append("' and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        //更新缓存
        OrderPayMemory.getInstance().modify(orderNo);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return true;
    }

    // 确认中
    private static ConcurrentHashMap<String, String> suringMap = new ConcurrentHashMap<>();

    //接单
    public static ResultInfo sureOrder(String sysAppKey, ShopInfo shopInfo, OrderInfo orderInfo, String opUsername, boolean sureBySystem) {
        ResultInfo resultInfo = new ResultInfo();
        String orderNo = orderInfo.getOrderNo();
        if (suringMap.containsKey(orderNo)) {
            return new ResultInfo("确认接单中，请稍后");
        }
        suringMap.put(orderNo, orderNo);
        int status = orderInfo.getOrderStatus();
        if (status == ORDER_STATUS.CANCEL
                || status == ORDER_STATUS.OVER
                || status == ORDER_STATUS.CANCEL_BY_SYSTEM
                || status == ORDER_STATUS.PAYED_CANCEL
                || status == ORDER_STATUS.SHOP_REFUSED
                || status == ORDER_STATUS.SHOP_SURE
                || status == ORDER_STATUS.SHOP_PUSH_GOODS//商家已发货，不能再接单
                || status == ORDER_STATUS.PEISONG
                || status == ORDER_STATUS.POSTMAN_PULL_GOODS//配送员已取货，不能再接单
                || status == ORDER_STATUS.POSTMAN_FINISH////配送员送达，不能再接单
                || status == ORDER_STATUS.POSTMAN_ZHIDING
                || status == ORDER_STATUS.POSTMAN_CANT_FINISH
                || status == ORDER_STATUS.POSTMAN_REFUSED
                || status == ORDER_STATUS.POSTMAN_DAODIAN
                || status == ORDER_STATUS.POSTMAN_SURE) {
            // todo  zhuwx
       /*     // 骑手是否可以在商家前接单
            if (!sureBySystem || (null != SYS_SETTINGS.POSTMAN_GARB_ORDER_BEFORE_SHOP && 0 == 1 - SYS_SETTINGS.POSTMAN_GARB_ORDER_BEFORE_SHOP)) {
                if (0 == ORDER_STATUS.POSTMAN_DAODIAN - orderInfo.getOrderStatus()
                        || 0 == ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP - orderInfo.getOrderStatus()
                        || 0 == ORDER_STATUS.POSTMAN_SURE - orderInfo.getOrderStatus()
                        || 0 == ORDER_STATUS.POSTMAN_REFUSED - orderInfo.getOrderStatus()
                        || 0 == ORDER_STATUS.POSTMAN_ZHIDING - orderInfo.getOrderStatus()) {
                    // 骑手可以在商家前接单，需要判断商家实际是否已接单，如果未接过单，需要一直在进行中显示
                    // 是否骑手可以在商家前接单
                    if (null != orderInfo.getShopSureBySys() && 0 == 1 - orderInfo.getShopSureBySys()) {
                        // 后台已为商家接单
                        return new ResultInfo("当前订单状态下不允许操作");
                    }
                    if (ValidateUtil.isAbsLong(orderInfo.getShopSureTime())) {
                        // 商家已接过单了
                        return new ResultInfo("当前订单状态下不允许操作");
                    }
                } else {
                    return new ResultInfo("当前订单状态下不允许操作");
                }
            } else {
                return new ResultInfo("当前订单状态下不允许操作");
            }*/
            suringMap.remove(orderNo);
            return new ResultInfo("当前订单状态下不允许操作");
        }

        String shopSureTime = ",shopSureTime=" + DateUtils.getCurrTime();
        if (sureBySystem) {
            shopSureTime = ",shopSureBySys=1";
        }
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            suringMap.remove(orderNo);
            return new ResultInfo("你选择的订单有误");
        }
        if (!OrderMan.modifyOrderStatus(opUsername, orderNo, ORDER_STATUS.SHOP_SURE, shopSureTime)) {
            suringMap.remove(orderNo);
            return new ResultInfo("操作失败，请稍后再试");
        }

        boolean isDaoDianPay = false;
        if (StringUtils.isNotEmpty(orderInfo.getExtra2()) && "scan_code".equalsIgnoreCase(orderInfo.getExtra2())) { // 到店支付订单
            isDaoDianPay = true;
            String shopFinishTime = ",shopFinishTime=" + DateUtils.getCurrTime();
            if (!OrderMan.modifyOrderStatus(opUsername, orderNo, ORDER_STATUS.SHOP_FINISH, shopFinishTime)) {
                return new ResultInfo("操作失败，请稍后再试V3");
            }
            //分成
            ResultInfo distributeResultInfo = OrderPay.distributeMoney(orderInfo, orderInfo.getOrderNo(), opUsername);// 到店支付订单，商家接单
            if (null != resultInfo && !distributeResultInfo.isSuccess()) {
                suringMap.remove(orderNo);
                System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
            }
        }
        if (OrderMan.isMultipleSonOrder(orderInfo)) {
            try {
                OrderMan.checkMultipleOrderAllShopSure(opUsername, orderInfo);
            } catch (Exception e) {
                e.printStackTrace();
                suringMap.remove(orderNo);
                System.out.println("聚合订单修改订单状态失败：" + e.getMessage());
            }
        }

        //商户订单量增加
        ShopMan.addShopOrderCounts(shopInfo.getId(), shopInfo.getOwnUsername(), opUsername);

        //删除商家未接单
        OrderInfoMemory.getInstance().removeShopNotSure(orderNo, orderInfo.getShopCity());

        //发送一条订单通知
//        Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），商家已接单");

        //如果是配送员提前接单的
        if (null != SYS_SETTINGS.POSTMAN_GARB_ORDER_BEFORE_SHOP && 0 == 1 - SYS_SETTINGS.POSTMAN_GARB_ORDER_BEFORE_SHOP && ValidateUtil.isNotNull(orderInfo.getPostManUsername())) {
            //配送员已提前接单
            //需要把订单状态改为配送员已抢单后的
            if (!OrderMan.modifyOrderStatus("admin", orderNo, ORDER_STATUS.POSTMAN_SURE, null)) {
                return new ResultInfo("操作失败，请稍后再试");
            }
        } else {
            //通知该城市所有配送员
            if (0 == ZI_QU_TYPE.PEI_SONG - orderInfo.getIsZiQu() && !OrderMan.isMultipleSonOrder(orderInfo) && !isDaoDianPay && (shopInfo.getIsSeriesSale() == null || shopInfo.getIsSeriesSale() != 2)) {
                OrderMan.orderJPushToPostman(orderInfo);
                // JPushMessage jPushMessage = new JPushMessage(true, orderInfo.getShopCity(), "又有新的订单了", "又有新的订单了，快去抢单吧");
                // jPushMessage.setPushUserType(JPushMessage.POSTMAN);//推给配送员
                // jPushMessage.setJpSubType("");
                // JPushTask.jPushMessageList.add(jPushMessage);
            }
//            JPushMessage jPushMessage = new JPushMessage(true, orderInfo.getShopCity(), "又有新的订单了", "又有新的订单了，快去抢单吧");
//            jPushMessage.setPushUserType(JPushMessage.POSTMAN);//推给配送员
//            JPushTask.jPushMessageList.add(jPushMessage);
        }

        //通知用户商家已接单
        if (!isDaoDianPay) {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），商家已接单", orderNo);
            // 接单自动打印
            autoPrint(shopInfo, orderInfo, sureBySystem);
        }

//        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），商家已接单");
//        // 接单自动打印
//        autoPrint(shopInfo, orderInfo);
        // 自动派单线程
        if (orderInfo.getShopSelfPost() == null || orderInfo.getShopSelfPost() == 0) {
            OrderTaskUtil.addNeedDispatchOrder(orderNo);
        }
        // 哒哒下单
        ShopOrderService.getInstance().sendDeliverOrderData(sysAppKey, orderInfo, true);

        suringMap.remove(orderNo);
        return resultInfo;
    }

    // 检测所有订单是否已经备货完成
    private static void checkAllOrderShopReady(OrderInfo orderInfo, String shopReadyTime, String opUser) {
        if (orderInfo == null || !OrderMan.isMultipleParentOrder(orderInfo)) {
            return;
        }
        HashSet<String> set = OrderInfoMemory.getInstance().listOfParentOrderNo(orderInfo.getOrderNo());
        boolean flag = true;
        for (String orderNo : set) {
            OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            if (info == null) {
                continue;
            }
            if (info.getOrderStatus() - ORDER_STATUS.SHOP_READY != 0) {
                flag = false;
                break;
            }
        }
        if (flag) {
            OrderMan.modifyOrderStatus(opUser, orderInfo.getOrderNo(), ORDER_STATUS.SHOP_READY, shopReadyTime);
        }
    }

    // 商家端自动打印接口
    private static void autoPrint(ShopInfo shopInfo, OrderInfo orderInfo, boolean sureBySystem) {
        if (shopInfo == null || orderInfo == null) {
            return;
        }
        if (shopInfo.getAutoPrint() != null && shopInfo.getAutoPrint() == 1) {
            // 打印
            PrintMan.print_message_(orderInfo.getOrderNo(), shopInfo.getId(), sureBySystem);
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = "/order/shop/shopNote")
    @ResponseBody
    public String order_shop_shopNote(String shopNote, String orderNo) {
        if (StringUtils.isBlank(orderNo)) {
            return AjaxResult.errorResult("订单编号不能为空");
        }
        if (StringUtils.isBlank(shopNote)) {
            return AjaxResult.errorResult("商家备注不能为空");
        }
        try {
            ShopOrderService.getInstance().shopNote(shopNote, orderNo);
            return AjaxResult.successResult();
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("商家备注失败,请稍后重试");
        }
    }
}
